package com.roy.workbench.bookmark.controller.v1;


import com.roy.workbench.bookmark.domain.Bookmark;
import com.roy.workbench.bookmark.domain.Catalog;
import com.roy.workbench.bookmark.service.BookmarkService;
import com.roy.workbench.bookmark.service.CatalogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by elloxxn on 12/6/2017.
 */
@RestController
@RequestMapping("/v1/catalogs")
public class CatalogControllerV1 {
    private static Logger logger = LoggerFactory.getLogger(CatalogControllerV1.class);
    @Autowired
    private CatalogService service;
    @Autowired
    private BookmarkService bookmarkService;
    @GetMapping
    public ResponseEntity<Page<Catalog>> find() {
        PageRequest pageRequest = new PageRequest(0, 20);
        Page<Catalog> page = service.query(pageRequest);
        return new ResponseEntity(page, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Catalog> findById(@PathVariable("id") Long id) {
        Catalog one = service.findById(id);
        logger.info("=========");
        return new ResponseEntity(one, HttpStatus.OK);
    }

    @GetMapping("/{id}/bookmarks")
    public ResponseEntity<Bookmark> findBookmarksById(@PathVariable("id") Long id) {
        List<Bookmark> list = bookmarkService.findByCatalogId(id);
        return new ResponseEntity(list, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<Catalog> create(@RequestBody Catalog catalog) {
        Catalog catalog1 = service.save(catalog);
        return new ResponseEntity(catalog1, HttpStatus.CREATED);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Catalog> deleteById(@PathVariable("id") Long id) {
        Catalog one = null;
        try {
            one = service.delete(id, true);
        } catch (Exception e) {
            return new ResponseEntity(null, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(one, HttpStatus.OK);
    }
}
